<?php

namespace control;
class inventoryAllotClass extends adIndexClass
{
    private const page = 'inventoryAllot';
    private const table = 'inventory_allot';
    private const tableMx = 'inventory_allot_detail';
    private const tableRecord = 'inventory_record';
    private const title = '调拨单';
    private const state = ['草稿', '待确认', '已确认'];

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'      => [
                        'name'  => '{l.inventoryAllot.homeSearch.orderNo}',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'outWarehouse' => [
                        'name'  => '{l.inventoryAllot.homeSearch.outWarehouse}',
                        'width' => 200,
                    ],
                    'inWarehouse'  => [
                        'name'  => '{l.inventoryAllot.homeSearch.inWarehouse}',
                        'width' => 200,
                    ],
                    'type'         => [
                        'name'  => '{l.inventoryAllot.homeSearch.type}',
                        'width' => 200,
                    ],
                    'num'          => [
                        'name'  => '{l.inventoryAllot.homeSearch.num}',
                        'width' => 200,
                    ],
                    'money'        => [
                        'name'  => '{l.inventoryAllot.homeSearch.money}（' . static::$unit . '）',
                        'width' => 200,
                    ],
                    'orderDate'    => [
                        'name'  => '{l.inventoryAllot.homeSearch.orderDate}',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'state'        => [
                        'name'  => '{l.inventoryAllot.homeSearch.state}',
                        'width' => 150,
                    ],
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    L('inventoryAllot.home.orderNo') => text(array("name" => "orderNo")),
                    L('inventoryAllot.home.outWarehouseId')   => selectMultiple(['table' => 'warehouse', 'where' => " coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql(), 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'outWarehouseId']),
                    L('inventoryAllot.home.inWarehouseId') => selectMultiple(['table' => 'warehouse', 'where' => " coid = '" . self::$coid . "' AND state = '启用' ", 'sqlField' => 'name', 'sqlId' => 'id', 'name' => 'inWarehouseId']),
                ],
                [
                    '调拨类型' => select(['name' => "type", 'option' => explode('，', para('inventoryAllotType'))]),
                    L('inventoryAllot.home.orderDate')   => text(['name' => 'orderDate', 'laydate' => ['range' => '~', 'type' => 'date']]),
                    L('inventoryAllot.home.state') => select(["name" => "state", 'option' => self::state]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home(): string
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . L('inventoryAllot.homeSearch.detail') . "','" . $url . "&fun=edit')\" class='spanButton'>" . L('inventoryAllot.homeSearch.new') . "</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">" . L('inventoryAllot.homeSearch.del') . "</span>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= " <span onclick=\"batchPrint('" . $this->get('cla') . "')\" class='spanButton'>" . L('inventoryAllot.homeSearch.batchPrint') . "</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch(): bool|string
    {
        //查询结果
        $where = " coid = '" . self::$coid . "' ";
        $equal = [
            'orderNo'        => $this->post('orderNo'),
            'outWarehouseId' => $this->post('outWarehouseId'),
            'inWarehouseId'  => $this->post('inWarehouseId'),
        ];
        $like  = [
            'type'  => $this->post('type'),
            'state' => $this->post('state'),
        ];
        $where .= self::getWarehouseSql('outWarehouseId');
        //生成查询语句
        $where .= search([
            "="    => $equal,
            "like" => $like,
        ]);
        if ($this->post('orderDate')) {
            $where .= self::timeComparison($this->post('orderDate'), 'date', 'orderDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page          = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
            );
        $isPrint  = $this->power(self::page, "print");
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate   = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => L('inventoryAllot.homeSearch.detail'), "click" => "newIframe('" . L('inventoryAllot.homeSearch.detail') . "','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
                "edit"   => $array['state'] == '草稿' ? ["title" => L('inventoryAllot.homeSearch.edit'), "click" => "newIframe('" . L('inventoryAllot.homeSearch.detail') . "','" . $url . "&fun=edit&id=" . $array['id'] . "')"] : [],
                'print'  => ($isPrint === true) ? ['title' => L('inventoryAllot.homeSearch.print'), 'click' => "window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage&id={$array['id']}')"] : [],
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "num":
                        $num   = find(array('table' => self::tableMx, 'where' => "orderId = '$array[id]'", 'sum' => "num"));
                        $row[] = self::lostZero($num, 'numPrecision');
                        break;
                    case "money":
                        $money = find(array('table' => self::tableMx, 'single' => " orderId = '$array[id]' ", 'field' => "ifnull(sum(num*price),0) as money"))['money'] ?: 0;
                        $row[] = self::formattingFigure($money);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = find([
            'table'  => self::tableMx,
            'single' => "orderId in (select id from ".self::table." where {$where})",
            'field'  => "ifnull(sum(num),0) as num,ifnull(sum(num*price),0) as money",
        ]);
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
            'money'   => self::formattingFigure($totalQuery['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 合并物料
     */
    public static function mergeMaterial($listId): array
    {
        $result = [];
        if (empty($listId)) {
            return $result;
        } else {
            $listArr = explode(',', $listId);
            foreach ($listArr as $id) {
                $machiningOrderMx = query('machining_order_detail', "id = '$id'");
                if (!array_key_exists($machiningOrderMx['materialId'], $result)) {
                    $result[$machiningOrderMx['materialId']] = [
                        'num'        => $machiningOrderMx['num'],
                        'unit'       => $machiningOrderMx['unit'],
                        'materialId' => $machiningOrderMx['materialId'],
                    ];
                } else {
                    //单位不同的相同物料转为第一个物料的单位
                    $machiningOrderMx['num']                        = machiningOrderClass::material_num_change(
                        $machiningOrderMx['materialId'],
                        $machiningOrderMx['unit'],
                        $result[$machiningOrderMx['materialId']]['unit'],
                        $machiningOrderMx['num']
                    );
                    $result[$machiningOrderMx['materialId']]['num'] = $result[$machiningOrderMx['materialId']]['num'] + $machiningOrderMx['num'];
                }
            }
        }
        return $result;
    }

    /**
     * 保存并提交
     * @return bool|string
     */
    public function saveAndCommit(): bool|string
    {
        $resultJson = $this->editEdit();
        $result     = json_decode($resultJson, true);
        if ($result['warn'] == 2) {
            unset($_SESSION['warn']);
            $resultJson = $this->commitEdit();
        }
        return $resultJson;
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $id       = $this->get('id')?:self::getId();
        $info     = query(self::table, " coid = '" . self::$coid . "' AND id = '" . $id . "' ");
        $button[] = [
            'style' => 'li-btn-blue-bg',
            "name"  => L('inventoryAllot.edit.save'),
            "type"  => "点击事件",
            "title" => L('inventoryAllot.edit.save'),
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
        ];
        $button[] = [
            "name"  => "保存并提交",
            "type"  => "点击事件",
            "title" => "保存",
            'fun'   => "subForm('" . self::page . "EditForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=saveAndCommit')"
        ];
        $tr[]     = ['', '{l.inventoryAllot.edit.code}', '{l.inventoryAllot.edit.name}', '{l.inventoryAllot.edit.model}', '{l.inventoryAllot.edit.unit}', '{l.inventoryAllot.edit.location}', '{l.inventoryAllot.edit.batch}', '{l.inventoryAllot.edit.inventory}', '{l.inventoryAllot.edit.num}', '{l.inventoryAllot.edit.price}（' . static::$unit . '）', '{l.inventoryAllot.edit.money}（' . static::$unit . '）', '{l.inventoryAllot.edit.text}'];
        $totalArr = ['num'=>0,'money'=>0];
        if ($this->get('source') == 'materialDemand') {
            //从材料需求生成
            /*$listId                 = $this->get('listId');
            $info['outWarehouseId'] = $this->get('warehouseId');
            $result                 = self::mergeMaterial($listId);//合并相同的物料
            foreach ($result as $array) {
                $material     = query('material', " id = '$array[materialId]'");
                $inventoryNum = inventoryBalanceClass::inventoryNum($material['id'], $info['outWarehouseId']);
                $unitPrice    = inventoryBalanceClass::unitPrice($material['id']);
                $money        = round($unitPrice * $array['num'], 2);
                $tr[]         = [
                    componentClass::tablePperation($k+1,"delTableRow(this)").
                    hidden(['name' => 'mxId[]', 'value' => self::getId()]) .
                    hidden(['name' => 'materialId[]', 'value' => $array['materialId'],]),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    select([
                        'name' => 'unit[]',
                        'option' => inventoryBalanceClass::materialUnit($array['materialId']),
                        'value' => $array['unit']
                    ]),
                    hidden(['name' => 'inventoryNum[]', 'value' => $inventoryNum]) . $inventoryNum,
                    text(['name' => 'num[]', 'value' => $array['num'], 'blur' => 'countMoney']),
                    $unitPrice,
                    "<span class='total'>$money</span>",
                    text(['name' => 'mxText[]'])
                ];
            }*/
        } else {
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
            foreach ((array)$result['array'] as $k=>$array) {
                $material = query('material', " id = '$array[materialId]'");
                // $inventoryNum = inventoryBalanceClass::inventoryNum($material['id']);
                $inventoryNum = $array['orderNum'];
                //$unitPrice    = inventoryBalanceClass::unitPrice($material['id']);
                $unitPrice = $array['price'];
                $money = self::formattingFigure($unitPrice*$array['num']);
                $tr[]         =
                    [
                        componentClass::tablePperation($k+1,"delTableRow(this);calculateTotal()").
                        hidden(['name' => 'mxId[]', 'value' => $array['id']]) .
                        hidden(['name' => 'concatId[]', 'value' => $array['positionId'] . '-' . $array['materialId'] . '-' . $array['batch']]),
                        $material['code'],
                        $material['name'],
                        $material['model'],
                        $array['unit'],
                        warehousePositionClass::getName($array['positionId']),
                        $array['batch'],
                        hidden(['name' => 'inventoryNum[]', 'value' => $inventoryNum]) . self::lostZero($inventoryNum, 'numPrecision'),
                        text([
                            'name'  => 'num[]',
                            'other' => self::digitalFiltering('numPrecision'),
                            'value' => self::lostZero($array['num'], 'numPrecision'),
                            'blur'  => 'countMoney'
                        ]),
                        "<span class='price'>$unitPrice</span>",
                        "<span class='total'>$money</span>",
                        text(['name' => 'mxText[]', 'value' => $array['text']])
                    ];
                $totalArr['num'] += $array['num'];
                $totalArr['money'] += $money;
            }
        }
        $total = [
            8 => "<span id='total_num'>".self::lostZero($totalArr['num'],'numPrecision')."</span>",
            10 => "<span id='total_money'>".self::lostZero($totalArr['money'])."</span>",
        ];
        $list               = $this->listTable(array('tr' => $tr, 'end' => true, 'total' => $total));
        $page               = self::page;
        $choiceMaterialWord = L('inventoryAllot.edit.choiceMaterial');
        $but = <<<EOT
                <span class="smallButton" onclick="layer('{$this->get('cla')}','addMx', $('form[name={$page}EditForm]').serialize())">$choiceMaterialWord</span>
EOT;

        //表单
        $data['button'] = $this->tableShowButton($button);
        $body = $this->edit4([
            '基本信息' => [
                [
                    must . L('inventoryAllot.edit.outWarehouse') => selectMultiple([
                            'table'    => 'warehouse',
                            "title"    => L('inventoryAllot.edit.outWarehouse'),
                            'where'    => " coid = '" . self::$coid . "' AND state = '启用' " . self::getWarehouseSql(),
                            'sqlField' => 'name',
                            'sqlId'    => 'id',
                            'name'     => 'outWarehouseId',
                            'value'    => $info['outWarehouseId'],
                            'change'   => 'assign'
                        ]) . hidden(['name' => 'outWarehouse', 'value' => $info['outWarehouse'],]),
                    must . L('inventoryAllot.edit.inWarehouse')  => selectMultiple([
                            'table'    => 'warehouse',
                            "title"    => L('inventoryAllot.edit.inWarehouse'),
                            'where'    => " coid = '" . self::$coid . "' AND state = '启用' ",
                            'sqlField' => 'name',
                            'sqlId'    => 'id',
                            'name'     => 'inWarehouseId',
                            'value'    => $info['inWarehouseId'],
                            'change'   => 'assign'
                        ]) . hidden(['name' => 'inWarehouse', 'value' => $info['inWarehouse']]),
                    must . L('inventoryAllot.edit.orderDate')    => text([
                        'name'    => "orderDate",
                        'class'   => 'text',
                        'value'   => $info['orderDate'] ?: $this->date,
                        'laydate' => []
                    ]),
                    L('inventoryAllot.edit.type') => select([
                        'name'   => "type",
                        'class'  => 'text',
                        'value'  => $info['type'],
                        'option' => explode('，', para('inventoryAllotType'))]),
                ],
                [
                    L('inventoryAllot.edit.text') => textarea(['name' => "text", 'class' => 'text', 'value' => $info['text']]),
                ],
            ]
        ]);
        $body .= $this->editList([
            'id' => 'materialTable',
            'title' => L('inventoryAllot.edit.allotMx'),
            'button' => $but,
            'html' => $list,
        ]);
        $data['html'] = $this->pageEdit([
            "html"  => $body,
            'hidden' => hidden(['name' => 'id', 'value' => $id]),
        ]);
        $data['html'] .= <<<EOT
<script>
//计算金额，税额等
function countMoney(e){
    let num = $(e).val()
    let price = $(e).parent().parent().find('.price').text()
    let total = num * price
    $(e).parent().parent().find(".total").html(total.toFixed(2))
    calculateTotal()
}

function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit', $("form[name='mxForm']").serialize(),function(res) {
        $("#materialTable tbody").append(res.html);
        resetNumber($("#materialTable"))
    },'json');
}
//计算总数量
function calculateTotal(){
    let table = $('.editList')
    let num = 0,
    money = 0
    table.find("[name='num[]']").each(function(index){
        if($(this).val()){
          num+=Number($(this).val());
        }
        var totalText = table.find(".total").eq(index).text()
        if(totalText){
            money+=Number(totalText);
        }
    })
    $("#total_num").text(num.toFixed(publicSettings.numPrecision.num));
    $("#total_money").text(money.toFixed(amountPrecision));
}
function assign(e) {
    let val = $(e).find("option:selected").text()
    let name = $(e).attr('name').replace('Id', '')
    $("[name="+name+"]").val(val);
}
</script>

EOT;
        //返回
        return $this->tab($data);
    }

    public function editEdit(): bool|string
    {
        $id          = $this->post('id') ?: self::getId();
        $mxIdArr     = $this->post('mxId') ?: [];
        $concatIdArr = $this->post('concatId');
        //$inventoryNumArr  = $this->post('inventoryNum');
        //$unitArr          = $this->post('unit');
        $numArr     = $this->post('num');
        $mxTextArr  = $this->post('mxText');
        $field      = [
            'outWarehouse'   => $this->post('outWarehouse'),
            'outWarehouseId' => $this->post('outWarehouseId'),
            'inWarehouseId'  => $this->post('inWarehouseId'),
            'inWarehouse'    => $this->post('inWarehouse'),
            'orderDate'      => $this->post('orderDate'),
            'type'           => $this->post('type'),
            'text'           => $this->post('text'),
        ];
        $annotation = [
            'outWarehouse'   => L('inventoryAllot.edit.outWarehouse'),
            'outWarehouseId' => L('inventoryAllot.edit.outWarehouse'),
            'inWarehouseId'  => L('inventoryAllot.edit.inWarehouse'),
            'inWarehouse'    => L('inventoryAllot.edit.inWarehouse'),
            'orderDate'      => L('inventoryAllot.edit.orderDate'),
            'type'           => L('inventoryAllot.edit.type'),
            'text'           => L('inventoryAllot.edit.text'),
        ];
        $rules      = [
            'outWarehouse'   => 'required',
            'outWarehouseId' => 'required',
            'inWarehouseId'  => 'required',
            'inWarehouse'    => 'required',
            'orderDate'      => 'required',
            // 'type'           => 'required',
            // 'text'           => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0]; // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        /***仓库允许零库存出库*/
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = L('inventoryAllot.editEdit.power');
        } elseif ($field['outWarehouseId'] == $field['inWarehouseId']) {
            $json['warn'] = L('inventoryAllot.editEdit.cannotSame');
        } elseif (static::is_null_array($mxIdArr)) {
            $json['warn'] = L('inventoryAllot.editEdit.allotMx');
        } elseif (static::is_null_array($concatIdArr)) {
            $json['warn'] = L('inventoryAllot.editEdit.allotMx');
        } elseif (static::is_null_array($numArr)) {
            $json['warn'] = L('inventoryAllot.editEdit.num');
        } elseif (!empty($info['id']) && $info['state'] == '已确认') {
            $json['warn'] = L('inventoryAllot.editEdit.stateError');
        } else {
            $this->startTrans();
            $isPass = true;//事务通过标志
            if (!$info['id']) {
                $orderNo      = codeTemplateClass::generateCode(self::page, [
                    'prefix' => 'DB' . date('Ymd'),
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => " AND coid = '" . self::$coid . "' ",
                ], $field);
                $field        = array_merge($field, [
                    'id'      => $id,
                    'orderNo' => $orderNo,
                    'state'   => '草稿',
                    'coid'    => self::$coid,
                    'stid'    => $this->control['stid'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            //添加或更新调拨单明细
            if (is_array($mxIdArr)) {
                foreach ($mxIdArr as $k => $nid) {
                    $mx                 = query(self::tableMx, "id = '$nid'");
                    $concatId           = explode('-', $concatIdArr[$k]);
                    $material           = query('material', "id = '$concatId[1]'");
                    $warehouse_position = query('warehouse_position', "id = '$concatId[0]'");
                    $numArr[$k]         = self::formattingFigure($numArr[$k], 'numPrecision');
                    $inventoryNum       = inventoryBalanceClass::inventoryNum($material['id'], $field['outWarehouseId'], $warehouse_position['id'], $concatId[2]);
                    if (!$outAllowZero && $inventoryNum < $numArr[$k]) {
                        $json['warn'] = str_replace(['{{code}}', '{{name}}', '{{model}}'], [$material['code'], $material['name'], $material['model']], L('inventoryAllot.editEdit.transfinite'));
                        goto resp;
                    }
                    if (!empty($mx['id'])) {
                        //更新
                        $warn = static::update([
                            "table" => self::tableMx,
                            "field" => [
                                'coid'         => self::$coid,
                                'materialId'   => $material['id'],
                                'positionId'   => $warehouse_position['id'],
                                'batch'        => $concatId[2],
                                'unit'         => $material['unit'],
                                'inventoryNum' => $inventoryNum,
                                'orderNum'     => $numArr[$k],
                                'num'          => $numArr[$k],
                                'price'        => inventoryBalanceClass::unitPrice($material['id']),
                                'text'         => $mxTextArr[$k],
                            ],
                            "where" => " id = '$nid'",
                        ]);
                    } else {
                        //新增
                        $warn = static::insert([
                            "table" => self::tableMx,
                            "field" => [
                                'id'           => $nid,
                                'coid'         => self::$coid,
                                'orderId'      => $id,
                                'materialId'   => $material['id'],
                                'positionId'   => $warehouse_position['id'],
                                'batch'        => $concatId[2],
                                'unit'         => $material['unit'],
                                'inventoryNum' => $inventoryNum,
                                'orderNum'     => $numArr[$k],
                                'num'          => $numArr[$k],
                                'price'        => inventoryBalanceClass::unitPrice($material['id']),
                                'text'         => $mxTextArr[$k],
                            ],
                        ]);
                    }
                    if (!in_array($warn, ['新增成功', '更新成功'])) {
                        $isPass       = false;
                        $json['warn'] = $warn;
                        break;
                    }
                }
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass) {
                $this->commitTrans();
                delete(['table' => self::tableMx, 'where' => " id not in ('" . implode("','", $mxIdArr) . "') and orderId = '$id'"]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('inventoryAllot.editEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            } else {
                $this->rollback();
            }
        }

        resp:
        return json_encode($json, 320);
    }


    /**
     * @return bool|string
     */
    public function addMx(): bool|string
    {
        if (static::isNull($this->post['outWarehouseId'])) {
            return json_encode(['warn' => L('inventoryAllot.addMx.choiceWarehouse'), 320]);
        }elseif (static::isNull($this->post['inWarehouseId'])) {
            return json_encode(['warn' => '请选择调入仓库', 320]);
        } else {
            $html   =
                text(array("name" => "position", "title" => "{l.inventoryAllot.addMx.location}")) .
                text(array("name" => "code", "title" => "{l.inventoryAllot.addMx.code}")) .
                text(array("name" => "materialName", "title" => "{l.inventoryAllot.addMx.materialName}")) .
                materialClass::typeSelect(name: 'typeId') .
                text(array("name" => "batch", "title" => "{l.inventoryAllot.addMx.batch}")) .
                hidden(['name' => 'concatId', 'value' => implode(',', (array)$this->post('concatId'))]) .
                hidden(["name" => "warehouseId", 'value' => $this->post('outWarehouseId')]);
            $button = "<input onclick=\"addRow();$('#" . self::page . "AddMx').remove()\" type='button' class='searchSub m-l-5' value='" . L('inventoryAllot.addMx.sub') . "'>";
            $html   = $this->search($html);
            return $this->layer(["title" => L('inventoryAllot.addMx.add'), "height" => 600, "width" => 1100, "html" => $html, "button" => $button]);
        }
    }

    /**
     *添加物料
     */
    public function addMxSearch(): string
    {
        $concatId = $this->post('concatId') ? explode(',', $this->post('concatId')) : [];
        $where    = " 1=1 and coid = '" . self::$coid . "' and concat(positionId,'-',materialId,'-',batch) not in ('" . implode("','", $concatId) . "')";
        $mwhere   = search([
            "like" => [
                'code'     => $this->post('code'),
                'name'     => $this->post('materialName'),
                'typePath' => $this->post('typeId'),
            ],
        ]);
        if ($mwhere) {
            $where .= " AND materialId IN (SELECT id FROM material WHERE coid = '" . self::$coid . "' $mwhere )  ";
        }
        $like  = [
            'batch' => $this->post('batch'),
        ];
        $equal = [
            'warehouseId' => $this->post('warehouseId')
        ];
        if ($this->post('position')) {
            $where .= " AND positionId IN (SELECT id FROM warehouse_position WHERE coid = '" . self::$coid . "' and name like '%" . $this->post('position') . "%')  ";
        }
        $where       .= search([
            "like" => $like,
            "="    => $equal,
        ]);
        $fieldArr    = self::resolveField([
            'field' => '`id`, `coid`, `warehouseId`, `positionId`, `materialId`, batch, SUM(num) as num, `time`',
            'group' => 'positionId,materialId,batch',
        ]);
        $where       .= $fieldArr['group'] . " having sum(num)>0";
        $page        = $this->page(["table" => 'inventory_record', 'field' => $fieldArr['field'], "where" => $where, 'pageNum' => 9, "order" => " time desc"]);
        $json['sql'] = $page['sql'];
        //获取表头
        $checkAll = $this->checkAll("mxForm", "mxId");
        $tr[]     = [$checkAll, '{l.inventoryAllot.addMxSearch.materialType}', '{l.inventoryAllot.addMxSearch.code}', '{l.inventoryAllot.addMxSearch.name}', '{l.inventoryAllot.addMxSearch.model}', '{l.inventoryAllot.addMxSearch.unit}', '{l.inventoryAllot.addMxSearch.location}', '{l.inventoryAllot.addMxSearch.batch}', '{l.inventoryAllot.addMxSearch.inventory}'];
        //获取记录
        foreach ($page['array'] as $array) {
            $dominate           = [
                "box" => ["name" => "mxId", "value" => $array['positionId'] . '-' . $array['materialId'] . '-' . $array['batch']],
            ];
            $material           = query('material', " id = '$array[materialId]'");
            $tr[]               = [
                $this->dominate($dominate),
                $material['typeName'],
                $material['code'],
                $material['name'],
                $material['model'],
                $material['unit'],
                warehousePositionClass::getName($array['positionId']),
                $array['batch'],
                self::lostZero($array['num'], 'numPrecision'),
            ];
        }
        $json['html'] = $page['hint'] .
            "<form name='mxForm'>" .
            hidden(['name' => 'warehouseId', 'value' => $this->post('warehouseId')]) .
            $this->tableMany(array("tr" => $tr, "showSort" => true, "page" => $page['para'])) .
            "</form>" .
            $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxIdArr     = $this->post('mxId');
        $warehouseId = $this->post('warehouseId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('inventoryAllot.addMxEdit.power');
        } elseif (empty($mxIdArr) || !is_array($mxIdArr)) {
            $json['warn'] = L('inventoryAllot.addMxEdit.choice');
        } else {
            $tr = [];
            foreach ($mxIdArr as $mxId) {
                $concatId           = explode('-', $mxId);
                $material           = query('material', " id = '$concatId[1]'");
                $warehouse_position = query('warehouse_position', " id = '$concatId[0]'", "id,orderId,name");
                $id                 = self::getId();
                $price              = inventoryBalanceClass::unitPrice($material['id']);
                $inventoryNum       = self::lostZero(inventoryBalanceClass::inventoryNum(
                    $material['id'],
                    $warehouse_position['orderId'],
                    $warehouse_position['id'],
                    $concatId[2]
                ), 'numPrecision');
                $tr[]              = [
                    componentClass::tablePperation('',"delTableRow(this);calculateTotal()").
                    hidden(array('name' => 'mxId[]', 'value' => $id)) .
                    hidden(array('name' => 'concatId[]', 'value' => $mxId)),
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $material['unit'],
                    $warehouse_position['name'],
                    $concatId[2],
                    $inventoryNum,
                    text(array('name' => 'num[]', 'blur' => 'countMoney', 'other' => self::digitalFiltering('numPrecision'), 'value' => '')).hidden(array("name"=>"inventoryNum[]","value"=>$inventoryNum)),
                    "<span class='price'>$price</span>",
                    "<span class='total'>0</span>",
                    text(array('name' => 'mxText[]')),
                ];
            }
            $json['html'] = $this->tableMany(array('tr' => $tr, 'thead' => false));
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }


    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " coid = '" . self::$coid . "' AND id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = L('inventoryAllot.detail.empty');
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] != '已确认') {
                if ($info['state'] == '草稿') {
                    //按钮
                    $button[] = [
                        "name"  => L('inventoryAllot.detail.edit'),
                        "type"  => "顶部页卡",
                        "title" => L('inventoryAllot.detail.editDetail'),
                        "url"   => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                        'style' => 'li-btn-blue-bg',
                    ];
                    //按钮
                    $button[] = [
                        "name" => L('inventoryAllot.detail.sub'),
                        "type" => "弹出层",
                        "cla"  => $this->get('cla'),
                        "fun"  => "operate",
                        "post" => ["act" => 'commit', "id" => $info['id']],
                    ];
                }
                //按钮
                $button[] = [
                    "name" => L('inventoryAllot.detail.del'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name"  => L('inventoryAllot.detail.sure'),
                    "type"  => "弹出层",
                    "cla"   => $this->get('cla'),
                    "fun"   => "operate",
                    "post"  => ["act" => 'confirm', "id" => $info['id']],
                    'style' => 'li-btn-blue-bg',
                ];
            }
            if ($this->power(self::page, "confirm") && $info['state'] == '待确认') {
                $button[] = [
                    "name" => L('inventoryAllot.detail.cancel'),
                    "type" => "弹出层",
                    "cla"  => $this->get('cla'),
                    "fun"  => "operate",
                    "post" => ["act" => 'cancel', "id" => $info['id']],
                ];
            }
            //操作记录
            $button[] = self::operateLogBut($info['id']);

            $mxtr[] = ['{l.inventoryAllot.detail.code}', '{l.inventoryAllot.detail.name}', '{l.inventoryAllot.detail.model}', '{l.inventoryAllot.detail.unit}', '{l.inventoryAllot.detail.location}', '{l.inventoryAllot.detail.batch}', '{l.inventoryAllot.detail.inventory}', '{l.inventoryAllot.detail.allotNum}', '{l.inventoryAllot.detail.price}（' . static::$unit . '）', '{l.inventoryAllot.detail.money}（' . static::$unit . '）', '{l.inventoryAllot.detail.text}'];
            $result = find(array('table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"));
            foreach ($result['array'] as $array) {
                $material     = query('material', " id = '$array[materialId]'");
                $inventoryNum = self::lostZero($array['inventoryNum'], 'numPrecision');
                $mxtr[]       = [
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    warehousePositionClass::getName($array['positionId']),
                    $array['batch'],
                    $inventoryNum,
                    self::lostZero($array['num'], 'numPrecision'),
                    self::lostZero($array['price'], 'pricePrecision'),
                    self::formattingFigure($array['num'] * $array['price']),
                    $array['text'],
                ];
            }
            $res  = find([
                'table'  => self::tableMx,
                'field'  => " IFNULL(sum(num), 0) as num, IFNULL(sum(num*price), 0) as total",
                'single' => "orderId = '$info[id]' group by orderId"
            ]);
            $nums = $total = 0;
            if (!static::isNull($res)) {
                $nums  = self::lostZero($res['num'], 'numPrecision');
                $total = self::formattingFigure($res['total']);
            }
            $total_tr = [
                    7=>$nums,
                    9=>$total
            ];
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow([
                '详细信息' => [
                    [
                        L('inventoryAllot.detail.outWarehouse') => $info['outWarehouse'],
                        L('inventoryAllot.detail.inWarehouse')  => $info['inWarehouse'],
                        L('inventoryAllot.detail.orderDate')    => $info['orderDate'],
                        L('inventoryAllot.detail.type') => $info['type'],
                    ],
                    [
                        L('inventoryAllot.detail.orderNo') => $info['orderNo'],
                        L('inventoryAllot.detail.stid')    => self::findStaff($info['stid']),
                        L('inventoryAllot.detail.state')   => $info['state']
                    ],
                    [
                        L('inventoryAllot.detail.text') => pre($info['text']),
                    ],
                ],
            ]);
            $data['html'] .= $this->detailList([
                'title' => L('inventoryAllot.detail.allotMx'),
                'html' => $this->listTable(array('tr' => $mxtr, 'showEmpty' => true, 'total' => $total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 确认
     */
    public function confirmEdit(): string
    {
        $id    = $this->post('id');
        $info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state'       => '已确认',
            'checkId'     => self::$stid,
            'confirmTime' => $this->time,
        ];
        /***仓库允许零库存出库*/
        $outAllowZero = optionSettingClass::getSettingItem('库存', 'outAllowZero');
        if (!$this->power(self::page, 'confirm')) {
            $json['warn'] = L('inventoryAllot.confirmEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('inventoryAllot.confirmEdit.empty');
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = L('inventoryAllot.confirmEdit.stateError');
        } else {
            $this->startTrans();
            $isPass       = true; // 事务通过标志
            $json['warn'] = static::update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"]) && $isPass === true) {
                $details = find([
                    'table' => self::tableMx,
                    'where' => " orderId = '{$info['id']}'",
                ]);
                foreach ($details['array'] as $value) {
                    // 转换主单位
                    $mainUnitNum = inventoryBalanceClass::toMainUnit($value['materialId'], $value['num'], $value['unit']);
                    // 判断库存
                    $inventoryNum = inventoryBalanceClass::inventoryNum($value['materialId'], $info['outWarehouseId'], $value['positionId'], $value['batch']);
                    $material     = query("material", " id = '$value[materialId]' ");
                    if (!$outAllowZero && $inventoryNum - $mainUnitNum < 0) {
                        $json['warn'] = str_replace(['{{materialName}}'], [$material['name']], L('inventoryAllot.confirmEdit.transfinite'));
                        goto resp;
                    }
                    //调拨出库
                    $recordOutId = self::getNo();
                    static::insert([
                        'table' => self::tableRecord,
                        'field' => [
                            'id'          => $recordOutId,
                            'coid'        => self::$coid,
                            'warehouseId' => $info['outWarehouseId'],
                            'positionId'  => $value['positionId'],
                            'materialId'  => $value['materialId'],
                            'batch'       => $value['batch'],
                            'num'         => -1 * $mainUnitNum,
                            'moveId'      => $info['id'],
                        ],
                    ]);
                    if (!empty($value['positionId'])) {
                        //判断库存是否用完，去掉入库id
                        inventoryBalanceClass::recordStockToLocation(
                            '',
                            [
                                'materialId'  => $value['materialId'],
                                'warehouseId' => $info['outWarehouseId'],
                                'positionId'  => $value['positionId'],
                                'batch'       => $value['batch']
                            ]
                        );
                    }
                    //调拨入库
                    $recordInId = self::getNo();
                    $positionId = inventoryBalanceClass::matchLocation($info['inWarehouseId']); //默认仓位
                    static::insert([
                        'table' => self::tableRecord,
                        'field' => [
                            'id'          => $recordInId,
                            'coid'        => self::$coid,
                            'warehouseId' => $info['inWarehouseId'],
                            'positionId'  => $positionId,
                            'materialId'  => $value['materialId'],
                            'batch'       => $value['batch'],
                            'num'         => $mainUnitNum,
                            'moveId'      => $info['id'],
                        ],
                    ]);
                    if (!empty($warehouse_position['id'])) inventoryBalanceClass::recordStockToLocation($recordInId, ['positionId' => $positionId]);
                }
                // 补出入库记录
                inventoryBalanceClass::otherToinventory(self::table, $id);
                $this->commitTrans();//提交事务
                auditingFollow([
                    "type"   => "调拨单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】确认",
                ]);
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('inventoryAllot.confirmEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 取消
     */
    public function cancelEdit(): string
    {
        $id    = $this->post('id');
        $info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state'       => '草稿',
            'checkId'     => '',
            'confirmTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $json['warn'] = L('inventoryAllot.confirmEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('inventoryAllot.confirmEdit.empty');
        } elseif ($info['state'] != '待确认') {
            $json['warn'] = '此调拨单不是待确认状态，不能撤回';
        } else {
            $json['warn'] = update([
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow(array(
                    "type"   => "调拨单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】取消",
                ));
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('inventoryAllot.cancelEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 提交
     */
    public function commitEdit(): string
    {
        $id    = $this->post('id');
        $info  = query(self::table, " coid = '" . self::$coid . "' AND id = '$id'");
        $field = [
            'state' => '待确认',
        ];
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = L('inventoryAllot.confirmEdit.power');
        } elseif (empty($info['id'])) {
            $json['warn'] = L('inventoryAllot.confirmEdit.empty');
        } elseif ($info['state'] != '草稿') {
            $json['warn'] = L('inventoryAllot.confirmEdit.stateError');
        } else {
            $json['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                auditingFollow([
                    "type"   => "调拨单",
                    "typeId" => $info['id'],
                    "text"   => "【{$this->control['name']}】提交",
                ]);

                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = str_replace(['{{staffName}}', '{{type}}', '{{id}}'], [$this->control['name'], $type, $id], L('inventoryAllot.commitEdit.log'));
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
                $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $info['id'];
            }
        }
        resp:
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): string
    {
        $act  = $this->post('act') ?? '';
        $pwd  = $word = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'confirm':
                $act      = 'confirm';
                $msg      = L('inventoryAllot.operate.confirm');
                $title    = L('inventoryAllot.operate.confirmTitle');
                $function = 'confirmEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'commit':
                $act      = 'edit';
                $msg      = L('inventoryAllot.operate.commit');
                $title    = L('inventoryAllot.operate.commitTitle');
                $function = 'commitEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            case 'cancel':
                $act      = 'cancel';
                $msg      = L('inventoryAllot.operate.cancel');
                $title    = L('inventoryAllot.operate.cancelTitle');
                $function = 'cancelEdit';
                $form     = self::page . 'OperateForm, detailForm';
                $power    = '';
                $word     = true;
                break;
            default:
                $act      = 'del';
                $msg      = L('inventoryAllot.operate.del');
                $title    = self::page . 'Delete';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm, quoForm';
                $power    = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = str_replace(['{{msg}}'], [$msg], L('inventoryAllot.operate.log'));
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return string
     */
    public function delete(): string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = L('inventoryAllot.operate.power');
        } elseif (empty($array)) {
            $json['warn'] = L('inventoryAllot.operate.noChoice');
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " coid = '" . self::$coid . "' AND id = '$id' ");
                if ($info['state'] == '已确认') {
                    $warn = L('inventoryAllot.operate.fail');
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::tableMx, "where" => " orderId = '$id' "));
                    delete(array("table" => 'auditing_follow', "where" => " typeId = '$id' "));
                    //返回
                    $warn = '删除成功';
                    $x++;
                }
                $text .= str_replace(['{{id}}'], [$info['id']], L('inventoryAllot.delete.text')) . $warn . "。<br>";
            }
            //添加日志
            $text = str_replace(['{{staffName}}'], [$this->control['name']], L('inventoryAllot.delete.log')) . "<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = str_replace(['{{x}}'], [$x], L('inventoryAllot.delete.warn'));
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 批量打印
     *
     * @return string
     */
    public function batchPrint(): string
    {
        $lists = $this->get('lists');
        if (empty($lists)) {
            exit(L('inventoryAllot.batchPrint.error'));
        } else {
            $listId = base64_decode($lists, true);
            $array  = explode(',', $listId);
            $data   = [];
            foreach ($array as $id) {
                $data[] = static::printPage($id, false);
            }
            return (new printTemplateClass())->start(self::page, $data);
        }
    }

    /**
     * 打印
     *
     * @return string
     */
    public function printPage($param = '', $isReturn = true): string|array
    {
        $id                     = $param ?: $this->get('id');
        $info                   = query(self::table, " id = '$id'");
        $info['companyName']    = query('company', "coid = '" . self::$coid . "'")['name']; //公司名称//公司名称
        $info['title']          = self::title;
        $info['printTime']      = $this->time;
        $info['stid']           = self::findStaff($info['stid']);
        $info['outWarehouseId'] = warehouseClass::getName($info['outWarehouseId']);
        $info['inWarehouseId']  = warehouseClass::getName($info['inWarehouseId']);
        $info['qr']             = 'source=' . self::page . 'Other&id=' . $info['id'];
        $info['orderDate']      = date('Y/m/d', strtotime($info['orderDate']) ?: strtotime($info['time']));
        $detail                 = find(['table' => self::tableMx, 'where' => "orderId = '$info[id]' order by time"])['array'];
        $items                  = [];
        $x                      = 1;
        $totalNum               = 0;
        $totalMoney             = 0;
        foreach ($detail as $array) {
            $material = query('material', "id = '$array[materialId]'");
            $items[]  = [
                'no'           => $x,
                'materialCode' => $material['code'],
                'materialName' => $material['name'],
                'model'        => $material['model'],
                'unit'         => $array['unit'],
                'num'          => self::lostZero($array['num'], 'numPrecision'),
                'price'        => self::lostZero($array['price'], 'pricePrecision'),
                'money'        => self::formattingFigure(floatval($array['num']) * floatval($array['price'])),
                'text'         => $array['text'],
            ];
            $x++;
            $totalNum   += floatval($array['num']);
            $totalMoney += self::formattingFigure(floatval($array['num']) * floatval($array['price']));
        }
        $append         = [
            'no'    => L('inventoryAllot.printPage.total'),
            'num'   => self::lostZero($totalNum, 'numPrecision'),
            'money' => $totalMoney,
        ];
        $items[]        = $append;
        $info['detail'] = $items;
        if ($isReturn) {
            return (new printTemplateClass())->start(self::page, $info);
        } else {
            return $info;
        }
    }
}
